package com.chaoli.reggie_diy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chaoli.reggie_diy.common.R;
import com.chaoli.reggie_diy.domain.User;
import com.chaoli.reggie_diy.service.UserService;
import com.chaoli.reggie_diy.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送手机短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //生成4位验证码
            String validateCode = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为：{}", validateCode);
            //调用aliyun短信服务完成发送短信
//            SMSUtils.sendMessage("瑞吉外卖", "", phone, validateCode);
//            //将验证码保存到session
//            httpSession.setAttribute(phone, validateCode);
            //将验证码保存到redis中
            redisTemplate.opsForValue().set(phone,validateCode,5, TimeUnit.MINUTES);
            return R.success("手机验证码发送成功！!");

        }
        return R.error("手机验证码发送失败@@");
    }

    /**
     * 移动端用户登录
     * <p>
     * 前端传来两个参数，其中一个参数在User里面有，另一个参数没有
     * 有两种方式来接收
     * 1.使用UserDto
     * 2.使用Map对象
     *
     * @param loginMap
     * @param httpSession
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> loginMap, HttpSession httpSession) {
        log.info("移动端用户登录接收到的参数：{}", loginMap.toString());
        String phone = loginMap.get("phone").toString();
        String code = loginMap.get("code").toString();
        //从session中获取保存的验证码
//        String codeSession = (String) httpSession.getAttribute(phone);
        //从redis中获取验证码
        String validateCode = redisTemplate.opsForValue().get(phone);
        if (validateCode == null || !validateCode.equals(code)) {
            // 登陆失败
            return R.error("登陆失败");
        }
        //登录成功
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        //判断是否为新用户，是的话就完成注册
        if (user == null) {
            // 因为user为空，所以直接创建user对象赋值给user
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        // 登陆成功，把seesion存进浏览器
        httpSession.setAttribute("user", user.getId());
        // 登陆成功，删除redis中缓存的验证码
        redisTemplate.delete(phone);
        return R.success(user);

    }


}
